import dayjs from 'dayjs'
import loginApi from '@/api/login'
import { getToken, removeToken, setToken } from './auth'
import { store } from '@/store'
export const refreshToken = () => {
  return new Promise((reslove, reject) => {
    // debugger
    // 验证当前token是否过期
    const refreshAfter =
      JSON.parse(localStorage.getItem('userInfo')!)?.lastLoginTime || null
    const nowTime = dayjs().valueOf()
    const isTimeout =
      refreshAfter && dayjs(refreshAfter).add(3, 'hour').valueOf()
    const token = getToken()!
    let newToken = ''
    if (refreshAfter && isTimeout > nowTime) {
      loginApi.refreshToken({ token }).then((response) => {
        if (response.data.code == '10000') {
          newToken = response.data.token
          setToken(response.data.token)
          return reslove(newToken)
        } else {
          store.dispatch('user/logout', 1)
          return reject(false)
        }
      })
    } else {
      return reject(false)
    }
  })
}
